#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>

using namespace std;

// 定义一个解决方案类，用于解决移除元素相关的问题
class Solution
{
public:
    // 计算最大可移除元素数量的函数
    int maxRemoval(vector<int> &nums, vector<vector<int>> &queries)
    {
        sort(queries.begin(), queries.end(), [](vector<int> &a, vector<int> &b)
             { return a[0] < b[0]; });
        priority_queue<int> pq;
        // 用于记录每个位置的差异值，长度比nums数组多1
        vector<int> diff(nums.size() + 1, 0);
        // 
        int sum_i = 0;
        // 用于遍历queries数组的索引
        int j = 0;
        for (int i = 0; i < nums.size(); i++)
        {
            sum_i += diff[i];
            while (j < queries.size())
            {
                if (i == queries[j][0])
                {
                    pq.push(queries[j][1]);
                    j++;
                    continue;
                }
                break;
            }
            // 当优先队列不为空，且队首元素大于等于当前索引i，并且当前累加值小于nums[i]时
            while (!pq.empty() && pq.top() >= i && sum_i < nums[i])
            {
                diff[pq.top() + 1] -= 1;
                sum_i += 1;
                pq.pop();
            }
            if (sum_i < nums[i])
            {
                return -1;
            }
        }
        return pq.size();
    }
};

int main()
{
    vector<int> nums = {2, 0, 2};

    vector<vector<int>> queries = {
        {0, 2},
        {0, 2},
        {1, 1}};

    Solution solution{};
    cout << solution.maxRemoval(nums, queries) << endl;
    return 0;
}